package com.nowcoder.community.controller;

import com.nowcoder.community.constant.CommunityConstant;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.util.CommunityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 分享网页为PDF或Image
 * @author 花木凋零成兰
 * @date 2024/3/31 21:00
 */
@Controller
@Slf4j(topic = "ShareController.class")
public class ShareController {

    @Resource
    private EventProducer eventProducer;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${community.alioss.bucket-name}")
    private String bucketName;

    @Value("${community.alioss.endpoint}")
    private String endpoint;


    /**
     * 分享网页
     * @param htmlUrl
     * @return
     */
    @RequestMapping(path = "/share", method = RequestMethod.GET)
    @ResponseBody
    public String share(String htmlUrl) {
        // 文件名
        String fileName = CommunityUtil.generateUUID();
        // 分享网页事件
        // 异步生成长图
        Map<String, Object> data = new HashMap<>();
        data.put("htmlUrl", htmlUrl);
        data.put("fileName", fileName);
        data.put("suffix", ".png");
        Event event = Event.builder()
                .topic(CommunityConstant.TOPIC_SHARE)
                .data(data)
                .build();
        eventProducer.fireEvent(event);

        // 返回访问路径
        Map<String, Object> map = new HashMap<>();
        // map.put("shareUrl", domain + contextPath + "/share/image/" + fileName);
        map.put("shareUrl", "https://" + bucketName + "." + endpoint + "/" + fileName + ".png");
        return CommunityUtil.getJSONString(0, null, map);
    }

    /**
     * 获取长图     (改用云服务 废弃)
     * @param fileName
     * @param response
     */
    @RequestMapping(path = "/share/image/{fileName}", method = RequestMethod.GET)
    public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        if (StringUtils.isBlank(fileName)) {
            throw new IllegalArgumentException("文件名不能为空!");
        }
        response.setContentType("image/png");
        File file = new File(wkImageStorage + "/" + fileName + ".png");
        try (
                OutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(file)
                ) {
            byte[] buffer = new byte[1024]; // 缓冲区
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            log.error("获取长图失败：" + e.getMessage());
        }
    }

}
